﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using MultiDAQ_Analysis.Util;
using MultiDAQ_Analysis.Model;

namespace MultiDAQ_Analysis.View
{
    public partial class WorkConditionForm : UIForm
    {
        private int channelCount;
        private List<ChannelData> channelDataList;

        public WorkConditionForm()
        {
            InitializeComponent();
        }

        private void WorkConditionForm_Load(object sender, EventArgs e)
        {
            channelCount = AppConfig.ChannelCount;
            LoadChannelData();
            SetupDataGridView();
            LoadDataToGrid();
            AdjustColumnWidths();

            this.mainTableLayout.RowStyles[0] = new RowStyle(SizeType.Absolute, 180);
            this.Size = new Size(840, 400);
        }

        private void LoadChannelData()
        {
            try
            {
                channelDataList = ChannelDataManager.LoadAllChannelData();

                // 确保有足够的通道数据
                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载通道数据失败：{ex.Message}");
                InitializeDefaultData();
            }
        }

        private void InitializeDefaultData()
        {
            channelDataList = new List<ChannelData>();
            for (int i = 0; i < channelCount; i++)
            {
                channelDataList.Add(new ChannelData { ChannelIndex = i });
            }
        }

        private void SetupDataGridView()
        {
            dgvConditions.Columns.Clear();
            dgvConditions.Rows.Clear();

            // 冻结第一列
            var paramColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "参数名称",
                Name = "Parameter",
                ReadOnly = true,
                Frozen = true,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                SortMode = DataGridViewColumnSortMode.NotSortable
            };
            dgvConditions.Columns.Add(paramColumn);

            // 通道列
            for (int i = 1; i <= channelCount; i++)
            {
                dgvConditions.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = $"通道{i}",
                    Name = $"Channel{i}",
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
                    SortMode = DataGridViewColumnSortMode.NotSortable
                });
            }

            // 设置列宽分配策略
            dgvConditions.Columns[0].FillWeight = 30;
            for (int i = 1; i <= channelCount; i++)
            {
                dgvConditions.Columns[i].FillWeight = 70 / channelCount;
            }

            string[] parameters = {
                "α 本底 / CPS",
                "β 本底 / CPS",
                "α 工作源效率 / %",
                "β 工作源效率 / %",
                "α 标准源效率 / %",
                "β 标准源效率 / %"
            };

            foreach (string param in parameters)
            {
                int rowIndex = dgvConditions.Rows.Add();
                dgvConditions.Rows[rowIndex].Cells[0].Value = param;

                for (int j = 1; j <= channelCount; j++)
                {
                    var cell = dgvConditions.Rows[rowIndex].Cells[j] as DataGridViewTextBoxCell;
                    cell.Value = "0";
                }
            }
        }

        private void LoadDataToGrid()
        {
            try
            {
                for (int c = 0; c < channelCount; c++)
                {
                    var channelData = channelDataList[c];
                    var workCondition = channelData.WorkConditions;

                    // 填充数据到表格
                    dgvConditions.Rows[0].Cells[c + 1].Value = workCondition.AlphaBackground.ToString("0.###");
                    dgvConditions.Rows[1].Cells[c + 1].Value = workCondition.BetaBackground.ToString("0.###");
                    dgvConditions.Rows[2].Cells[c + 1].Value = workCondition.AlphaWorkEfficiency.ToString("0.###");
                    dgvConditions.Rows[3].Cells[c + 1].Value = workCondition.BetaWorkEfficiency.ToString("0.###");
                    dgvConditions.Rows[4].Cells[c + 1].Value = workCondition.AlphaStandardEfficiency.ToString("0.###");
                    dgvConditions.Rows[5].Cells[c + 1].Value = workCondition.BetaStandardEfficiency.ToString("0.###");
                }

                // 加载全局设置
                if (channelDataList.Count > 0)
                {
                    var firstChannelData = channelDataList[0].WorkConditions;
                    txtK.Text = firstChannelData.CorrectionFactor.ToString("0.###");
                    txtCycle.Text = firstChannelData.MeasurementCycle.ToString();
                    txtTime.Text = firstChannelData.MeasurementTime.ToString("0.###");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载数据到表格失败：{ex.Message}");
            }
        }

        private void SaveDataFromGrid()
        {
            try
            {
                // 从表格获取数据并更新到模型
                for (int c = 0; c < channelCount; c++)
                {
                    var channelData = channelDataList[c];
                    var workCondition = channelData.WorkConditions;

                    // 解析表格数据
                    if (double.TryParse(dgvConditions.Rows[0].Cells[c + 1].Value?.ToString(), out double alphaBackground))
                        workCondition.AlphaBackground = alphaBackground;

                    if (double.TryParse(dgvConditions.Rows[1].Cells[c + 1].Value?.ToString(), out double betaBackground))
                        workCondition.BetaBackground = betaBackground;

                    if (double.TryParse(dgvConditions.Rows[2].Cells[c + 1].Value?.ToString(), out double alphaWorkEff))
                        workCondition.AlphaWorkEfficiency = alphaWorkEff;

                    if (double.TryParse(dgvConditions.Rows[3].Cells[c + 1].Value?.ToString(), out double betaWorkEff))
                        workCondition.BetaWorkEfficiency = betaWorkEff;

                    if (double.TryParse(dgvConditions.Rows[4].Cells[c + 1].Value?.ToString(), out double alphaStdEff))
                        workCondition.AlphaStandardEfficiency = alphaStdEff;

                    if (double.TryParse(dgvConditions.Rows[5].Cells[c + 1].Value?.ToString(), out double betaStdEff))
                        workCondition.BetaStandardEfficiency = betaStdEff;

                    // 更新全局设置（每个通道都保存相同的全局设置）
                    if (double.TryParse(txtK.Text, out double correctionFactor))
                        workCondition.CorrectionFactor = correctionFactor;

                    if (int.TryParse(txtCycle.Text, out int measurementCycle))
                        workCondition.MeasurementCycle = measurementCycle;

                    if (double.TryParse(txtTime.Text, out double measurementTime))
                        workCondition.MeasurementTime = measurementTime;
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"解析表格数据失败：{ex.Message}");
                throw;
            }
        }

        private void AdjustColumnWidths()
        {
            if (dgvConditions.Columns.Count == 0) return;

            // 计算参数列的最佳宽度
            int maxWidth = 0;
            foreach (DataGridViewRow row in dgvConditions.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    int textWidth = TextRenderer.MeasureText(
                        row.Cells[0].Value.ToString(),
                        dgvConditions.Font).Width;

                    if (textWidth > maxWidth)
                        maxWidth = textWidth;
                }
            }

            // 添加边距并设置宽度
            maxWidth += 30;
            dgvConditions.Columns[0].Width = maxWidth;

            // 设置通道列的最小宽度
            int minChannelWidth = 80;
            for (int i = 1; i < dgvConditions.Columns.Count; i++)
            {
                if (dgvConditions.Columns[i].Width < minChannelWidth)
                {
                    dgvConditions.Columns[i].Width = minChannelWidth;
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!ValidateInputs())
            {
                return;
            }

            try
            {
                // 保存表格数据到模型
                SaveDataFromGrid();

                // 保存到文件
                if (ChannelDataManager.SaveAllChannelData(channelDataList))
                {
                    UIMessageBox.ShowSuccess("工作条件保存成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    UIMessageBox.ShowError("保存工作条件失败！");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存失败：{ex.Message}");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private bool ValidateInputs()
        {
            // 全局设置验证
            if (!double.TryParse(txtK.Text, out double k) || k <= 0)
            {
                UIMessageBox.ShowError("校正系数必须为正数");
                txtK.Focus();
                return false;
            }

            if (!int.TryParse(txtCycle.Text, out int cycle) || cycle <= 0)
            {
                UIMessageBox.ShowError("测量周期必须为正整数");
                txtCycle.Focus();
                return false;
            }

            if (!double.TryParse(txtTime.Text, out double time) || time <= 0)
            {
                UIMessageBox.ShowError("测量时间必须为正数");
                txtTime.Focus();
                return false;
            }

            // 数据网格验证
            //foreach (DataGridViewRow row in dgvConditions.Rows)
            //{
            //    if (row.IsNewRow) continue;

            //    for (int i = 1; i < dgvConditions.Columns.Count; i++)
            //    {
            //        if (row.Cells[i].ReadOnly) continue;

            //        string value = row.Cells[i].Value?.ToString();
            //        if (string.IsNullOrWhiteSpace(value) ||
            //            !double.TryParse(value, out double num) ||
            //            num < 0)
            //        {
            //            UIMessageBox.ShowError($"无效数值：第{row.Index + 1}行 {dgvConditions.Columns[i].HeaderText}");
            //            dgvConditions.CurrentCell = row.Cells[i];
            //            return false;
            //        }
            //    }
            //}

            return true;
        }

        private void WorkConditionForm_SizeChanged(object sender, EventArgs e)
        {
            if (dgvConditions.Columns.Count > 0)
            {
                AdjustColumnWidths();
            }
        }

        // 公开方法：获取指定通道的工作条件数据
        public WorkConditionData GetChannelWorkConditions(int channelIndex)
        {
            if (channelIndex >= 0 && channelIndex < channelDataList.Count)
            {
                return channelDataList[channelIndex].WorkConditions;
            }
            return new WorkConditionData();
        }

        // 公开方法：重新加载数据
        public void RefreshData()
        {
            LoadChannelData();
            LoadDataToGrid();
        }

        // 公开方法：导出数据到文件
        public void ExportData(string filePath)
        {
            try
            {
                SaveDataFromGrid();
                string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(channelDataList, Newtonsoft.Json.Formatting.Indented);
                System.IO.File.WriteAllText(filePath, jsonContent);
                UIMessageBox.ShowSuccess("数据导出成功！");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"导出数据失败：{ex.Message}");
            }
        }

        // 公开方法：从文件导入数据
        public void ImportData(string filePath)
        {
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    string jsonContent = System.IO.File.ReadAllText(filePath);
                    var importedData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChannelData>>(jsonContent);

                    if (importedData != null && importedData.Count >= channelCount)
                    {
                        channelDataList = importedData;
                        LoadDataToGrid();
                        UIMessageBox.ShowSuccess("数据导入成功！");
                    }
                    else
                    {
                        UIMessageBox.ShowError("导入的数据格式不正确或通道数量不匹配！");
                    }
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"导入数据失败：{ex.Message}");
            }
        }
    }
}
